package com.example.hibernate.demo.controller;

import com.example.hibernate.demo.util.Java21Features;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 这个控制器展示了Java 21的新特性
 */
@RestController
@RequestMapping("/api/java21")
@RequiredArgsConstructor
public class Java21DemoController {

    private final Java21Features java21Features;
    
    /**
     * 展示Java 21的虚拟线程功能
     */
    @GetMapping("/virtual-threads")
    public ResponseEntity<Map<String, Object>> virtualThreadsDemo() {
        Map<String, Object> result = new HashMap<>();
        
        // 启动一个后台任务来演示虚拟线程
        CompletableFuture.runAsync(java21Features::demonstrateVirtualThreads);
        
        result.put("message", "虚拟线程演示已启动，请查看服务器日志");
        result.put("info", "Java 21的虚拟线程允许创建数百万个轻量级线程，非常适合IO密集型应用");
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 展示Java 21的记录模式匹配功能
     */
    @GetMapping("/record-patterns")
    public ResponseEntity<Map<String, Object>> recordPatternsDemo() {
        Map<String, Object> result = new HashMap<>();
        
        // 创建测试对象
        Java21Features.Point point = new Java21Features.Point(10, 20);
        Java21Features.ColoredPoint coloredPoint = new Java21Features.ColoredPoint(new Java21Features.Point(30, 40), "红色");
        
        // 使用记录模式匹配
        String pointResult = java21Features.demonstrateRecordPatterns(point);
        String coloredPointResult = java21Features.demonstrateRecordPatterns(coloredPoint);
        
        result.put("pointResult", pointResult);
        result.put("coloredPointResult", coloredPointResult);
        result.put("info", "Java 21的记录模式匹配允许在switch表达式中解构记录类型");
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 展示Java 21的字符串模板功能
     */
    @GetMapping("/string-templates")
    public ResponseEntity<Map<String, Object>> stringTemplatesDemo(
            @RequestParam(defaultValue = "张三") String name,
            @RequestParam(defaultValue = "25") int age) {
        Map<String, Object> result = new HashMap<>();
        
        // 使用字符串模板
        String greeting = java21Features.demonstrateStringTemplates(name, age);
        
        result.put("greeting", greeting);
        result.put("info", "Java 21的字符串模板提供了一种更简洁的方式来创建包含表达式的字符串");
        
        return ResponseEntity.ok(result);
    }
}